package com.javaee.controlller;
import com.javaee.domain.User;
import com.javaee.service.userService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class userController {

    @Autowired
    private userService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@ModelAttribute User user, Model model, HttpSession session) {
        String result = userService.login(user);
        if (result.equals("验证成功")) {
            session.setAttribute("user", user);
            return "redirect:/activity";
        } else {
            model.addAttribute("error", result);
            return "login";
        }
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }
    @PostMapping("/register")
    public String register(@ModelAttribute User user, Model model) {
        String result = userService.register(user);
        if (result.equals("注册成功")) {
            model.addAttribute("error", result);
            return "login";
        } else {
            model.addAttribute("error", result);
            return "register";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate(); // 清除session
        return "redirect:/login";
    }
}